<template>
  <div class="app-container ohn transaction-box">
    <div class="f22 pointer" @click="goBack()">
      <i class="el-icon-arrow-left" />【{{ testTrade.name }}】测试报告单
    </div>
    <el-divider class="mt50" content-position="left">基本信息</el-divider>
    <el-form
      ref="reportCreateForm"
      v-loading="formLoading"
      class="mt36"
      :inline="true"
      :model="reportCreateForm"
      status-icon
      :rules="rules"
      label-width="150px"
    >
      <el-form-item :label="'报告编号\nreportNum'" prop="reportNum">
        <el-input
          v-model="reportCreateForm.reportNum"
          placeholder="请输入报告编号"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'时间\nDate'" prop="gmtCreate">
        <el-date-picker
          v-model="reportCreateForm.gmtCreate"
          type="date"
          placeholder="请选择时间"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'客户名称\nclient'" prop="client">
        <el-input
          v-model="reportCreateForm.client"
          placeholder="请输入客户名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'地    址\naddress'" prop="address">
        <el-input
          v-model="reportCreateForm.address"
          placeholder="请输入地址"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'样品名称\nsampleName'" prop="sampleName">
        <el-input
          v-model="reportCreateForm.sampleName"
          placeholder="请输入样品名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'样品型号\nsampleModel'" prop="sampleModel">
        <el-input
          v-model="reportCreateForm.sampleModel"
          placeholder="请输入样品型号"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'商    标\nbrand'" prop="brand">
        <el-input
          v-model="reportCreateForm.brand"
          placeholder="请输入商    标"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'供 应 商\nsupplier'" prop="supplier">
        <el-input
          v-model="reportCreateForm.supplier"
          placeholder="请输入供 应 商"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'订 单 号\norderNum'" prop="orderNum">
        <el-input
          v-model="reportCreateForm.orderNum"
          placeholder="请输入订 单 号"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'购 买 商\nbuyer'" prop="buyer">
        <el-input
          v-model="reportCreateForm.buyer"
          placeholder="请输入购 买 商"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'生 产 商\nproducers'" prop="producers">
        <el-input
          v-model="reportCreateForm.producers"
          placeholder="请输入生 产 商"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'出 口 地\nexportPlace'" prop="exportPlace">
        <el-input
          v-model="reportCreateForm.exportPlace"
          placeholder="请输入出 口 地"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item
        :label="'生 产 国\nproducingCountry'"
        prop="producingCountry"
      >
        <el-input
          v-model="reportCreateForm.producingCountry"
          placeholder="请输入生 产 国"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <p class="remark-content">
        以上信息由申请者提供及确认，我司对其真实性不承担责任
      </p>

      <el-form-item :label="'接收日期\nreceivingDate'" prop="receivingDate">
        <el-date-picker
          v-model="reportCreateForm.receivingDate"
          type="date"
          placeholder="请选择接收日期"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'检测周期\nDate'" prop="gmtOutput">
        <el-date-picker
          v-model="reportCreateForm.gmtOutput"
          type="daterange"
          :picker-options="reportCreateForm.gmtOutput"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'批准人\napprover'" prop="approver">
        <el-input
          v-model="reportCreateForm.approver"
          placeholder="请输入批准人"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'审核人\nreviewer'" prop="reviewer">
        <el-input
          v-model="reportCreateForm.reviewer"
          placeholder="请输入审核人"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'编制人\nreviewer'" prop="reviewer">
        <el-input
          v-model="reportCreateForm.reviewer"
          placeholder="请输入编制人"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'检测结果备注\nDate'" prop="gmtOutput">
        <el-input
          v-model="reportCreateForm.testRemark.test"
          type="textarea"
          placeholder="请输入检测结果备注"
          :rows="2"
          maxlength="100"
          show-word-limit
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-divider content-position="left">样品描述</el-divider>

      <vxe-toolbar ref="xToolbar">
        <template #tools>
          <el-button
            type="primary"
            size="small"
            plain
            @click="insertEvent"
          >新增</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        border
        show-footer
        show-overflow
        class="editable-footer mb20"
        :merge-footer-items="mergeFooterItems"
        :row-config="{ isHover: true }"
        :export-config="{}"
        :footer-cell-class-name="footerCellClassName"
        :data="reportCreateForm.sampleDesc"
        :edit-config="{ trigger: 'click', mode: 'row' }"
        @edit-closed="editClose"
      >
        <vxe-column type="seq" width="60" :title="'序号\nNum'" align="right" />
        <vxe-column
          field="sampleNum"
          :title="'样品编号\nStyle/Item No'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.sampleNum"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="sampleDes"
          :title="'样品描述\nReport No'"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input v-model="row.sampleDes" type="text" />
          </template>
        </vxe-column>
        <vxe-column
          field="sampleLocation"
          :title="'取样部位(位置)\nProduct Description'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
          width="160"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.sampleLocation"
              type="text"
              :min="1"
              :max="120"
              @change="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column title="操作" width="80">
          <template #default="{ row }">
            <el-button
              type="text"
              status="primary"
              @click="saveEvent(row)"
            >删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <el-divider content-position="left">检测结果</el-divider>
      <div
        v-for="(item, index) in reportCreateForm.testExperiment"
        :key="index"
      >
        <div>
          <div>{{ index + 1 }}.{{ item.title }}</div>
          <div>{{ item.method }}</div>
        </div>
        <div v-for="(items, indexs) in item.result" :key="indexs">
          <vxe-toolbar ref="xToolbar">
            <template #buttons>
              <div>{{ items.resultDetail }}</div>
            </template>
            <template #tools>
              <el-button
                type="primary"
                size="small"
                plain
                @click="insertEvent"
              >新增</el-button>
            </template>
          </vxe-toolbar>
          <vxe-table
            ref="xTable"
            border
            show-footer
            show-overflow
            class="editable-footer mb20"
            :merge-footer-items="mergeFooterItems"
            :row-config="{ isHover: true }"
            :export-config="{}"
            :footer-cell-class-name="footerCellClassName"
            :data="items.testItems"
            :edit-config="{ trigger: 'click', mode: 'row' }"
            @edit-closed="editClose"
          >
            <vxe-column
              type="seq"
              width="60"
              :title="'序号\nNum'"
              align="right"
            />
            <vxe-column
              field="testItem"
              :title="'检测项目\nReport No'"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input v-model="row.testItem" type="text" />
              </template>
            </vxe-column>
            <vxe-column
              field="CAS_num"
              :title="'CAS编号\nProduct Description'"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
              width="160"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.CAS_num"
                  type="text"
                  :min="1"
                  :max="120"
                  @change="updateFooterEvent"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="unit"
              :title="'单位\nStyle/Item No'"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.unit"
                  type="text"
                  @input="updateFooterEvent"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="threshold"
              :title="'方法检出限\nMaterial/Color'"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.threshold"
                  type="text"
                  @input="updateFooterEvent"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="limit"
              :title="'限值\nMaterial/Color'"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.limit"
                  type="text"
                  @input="updateFooterEvent"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="result"
              :title="'01\nMaterial/Color'"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.result"
                  type="text"
                  @input="updateFooterEvent"
                />
              </template>
            </vxe-column>
            <vxe-column title="操作" width="80">
              <template #default="{ row }">
                <el-button
                  type="text"
                  status="primary"
                  @click="saveEvent(row)"
                >删除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
      <el-form-item>
        <div class="tr">
          <el-button
            v-loading="formLoading"
            type="primary"
            @click="submitForm('reportCreateForm')"
          >保存</el-button>
          <el-button @click="resetForm('reportCreateForm')">重置</el-button>
        </div>
      </el-form-item>
    </el-form>
    <div class="remark-content">
      <!-- <p>{{reportCreateForm.testRemark.test}}</p> -->
      <p>本报告仅对收到的样品负责。</p>
      <p>本报告所包含的测试结果仅供客户参考。（盖章删）</p>
      <p>本报告无检测报告专用章、审核人、批准人签名无效。</p>
      <p>本报告不得作为商业广告使用。</p>
      <p>
        未经本公司书面统一，不得部分复制报告（全部复制除外）。任何未经授权的修改、伪造本文件的内容或外观都是非法的，违法者将被依法诉讼
      </p>
    </div>
  </div>
</template>

<script>
import methods from "./pub_methods/validate"
export default {
  data() {
    return {
      formLoading: false,
      testTrade: {
        name: "",
        id: "",
        status: ""
      },
      rules: {},
      reportCreateForm: {
        reportNum: "XJ1234",
        client: "新疆乐远儿童玩具",
        sampleName: "儿童玩具",
        address: "新疆乌鲁木齐人民路298号",
        sampleModel: "3-5岁",
        brand: "乐远",
        supplier: "新疆欢乐世界儿童玩具制造有限公司",
        orderNum: "123",
        buyer: "新疆乐远",
        producers: "新疆欢乐世界",
        exportPlace: "美国",
        producingCountry: "中国",
        testTradeId: "5",
        receivingDate: "2022-01-01 12:00:00",
        testStartDate: "2022-03-01 12:00:00",
        testEndDate: "2022-04-01 12:00:00",
        approver: "潘周聃",
        reviewer: "毛倩霞",
        editor: "曾旭芳",
        sampleDesc: [
          {
            sampleNum: "01",
            sampleDes: "样品描述xxx",
            sampleLocation: "恐龙玩具"
          }
        ],
        testExperiment: [
          {
            title: "1.邻苯二甲酸盐",
            method: "EN 14372: 2004",
            result: [
              {
                resultDetail:
                  "以下3种邻苯二甲酸盐（或酯）针对所有产品材料包括可放入口中的儿童玩具或儿童护理产品（豁免产品材料除外）",
                testItems: [
                  {
                    testItem: "邻苯二甲酸二异丁酯(DIBP)",
                    CAS_num: "84-69-5",
                    unit: "mg/kg",
                    threshold: "30",
                    limit: "1000",
                    result: "未检出"
                  },
                  {
                    testItem: "邻苯二甲酸二丁酯(DBP)",
                    CAS_num: "84-74-2",
                    unit: "mg/kg",
                    threshold: "30",
                    limit: "1000",
                    result: "未检出"
                  },
                  {
                    testItem: "邻苯二甲酸丁基苄基酯(BBP)",
                    CAS_num: "85-68-7",
                    unit: "mg/kg",
                    threshold: "30",
                    limit: "1000",
                    result: "未检出"
                  }
                ],
                conclusion: "合格"
              },
              {
                resultDetail:
                  "以下2种邻苯二甲酸盐适用于可放入口中的儿童玩具和儿童护理产品。",
                testItems: [
                  {
                    testItem: "邻苯二甲酸二正辛酯(DNOP)",
                    CAS_num: "117-84-0",
                    unit: "mg/kg",
                    threshold: "30",
                    limit: "-",
                    result: "未检出"
                  },
                  {
                    testItem: "",
                    CAS_num: "28553-12-0",
                    unit: "mg/kg",
                    threshold: "30",
                    limit: "-",
                    result: "未检出"
                  }
                ],
                conclusion: "合格"
              }
            ]
          }
        ],
        testRemark: {
          test: "1.0.1% =1000mg/kg；未检出指结果小于方法检出限"
        }
      },
      mergeFooterItems: [
        { row: 0, col: 0, rowspan: 0, colspan: 8 }
        // { row: 0, col: 1, rowspan: 9, colspan: 9 },
      ],
      customerOptions: [
        { key: 1, value: "中文纸质档" },
        { key: 2, value: "中文电子档" },
        { key: 3, value: "英文电子档" },
        { key: 4, value: "英文纸质档" }
      ]
    }
  },
  created() {
    this.testTrade.name = this.$route.query.name
    this.testTrade.id = this.$route.query.id
    this.testTrade.status = this.$route.query.status
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.reportCreateForm.testTradeId = this.testTrade.id
          this.formLoading = true
          this.$store
            .dispatch("transaction/saveTestReport", this.reportCreateForm)
            .then((res) => {
              const { data, success, errorMessage } = res
              if (success) {
                this.$refs[formName].resetFields()
                this.$message.success(data.msg)
              } else {
                this.$message.error(errorMessage)
              }
            })
            .catch(() => {})
            .finally(() => {
              this.formLoading = false
            })
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    goBack() {
      this.$router.push({
        path: "/detection/list"
      })
    },
    footerCellClassName({ $rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        if ($rowIndex === 0) {
          return "col-blue"
        }
      }
      if (columnIndex === 2) {
        if ($rowIndex === 1) {
          return "col-red"
        }
      }
    },
    // 在值发生改变时更新表尾合计
    updateFooterEvent() {
      const $table = this.$refs.xTable
      $table.updateFooter()
    },

    insertEvent() {
      // if (this.allowAdd) {
      //   const record = {
      //     text: "",
      //     label: "",
      //     operation: "",
      //     objectId: undefined
      //   };
      //   const { row: newRow } = await this.$refs.xTable.insert(record, row);
      //   await this.$refs.xTable.setActiveCell(newRow, "text");
      // }
      const $table = this.$refs.xTable
      const record = {
        testQuotationId: "",
        reportNum: "124",
        productDes: "34",
        style: "34",
        materialColor: "44",
        testItem: "54",
        unitPrice: "6",
        qty: "7",
        amountRmb: "6"
      }
      $table.insert(record).then(({ row }) => {
        $table.setActiveCell(row, "age")
      })
    },
    // 编辑单元格事件
    async editClose({
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex
    }) {
      const errMap = await this.$refs.xTable
        .validate(true)
        .catch((errMap) => errMap)
      if (errMap) {
        this.allowAdd = false
      } else {
        this.allowAdd = true
      }
    },
    saveEvent() {
      const $table = this.$refs.xTable
      const { insertRecords, removeRecords, updateRecords } =
        $table.getRecordset()
      VXETable.modal.alert(
        `insertRecords=${insertRecords.length} removeRecords=${removeRecords.length} updateRecords=${updateRecords.length}`
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.transaction-box {
  .el-form .el-form-item__label {
    background-color: red;
    line-height: 20px !important;
  }
  .el-form-item--medium .el-form-item__label {
    line-height: 20px !important;
  }
  .remark-content {
    font-size: 12px;
    color: #808080;
    line-height: 20px;
  }
}
</style>
